#define _CRT_SECURE_NO_WARNINGS

#include "my_homework_function.h"

// 01
int change_number(int num) {
    int sum = 0;
    int i = 0;
    while (num) {
        int bit = num % 10;
        bit %= 2;
        sum += bit * pow(10, i);
        i++;
        num /= 10;
    }
    return sum;
}

// 02
void print_right_triangle(int length) {
    for (int i = 0; i < length; i++) {
        for (int j = 0; j < length; j++) {
            if (i + j < length - 1) {
                printf("  ");
            }else {
                printf("* ");
            }
        }
        printf("\n");
    }
}

// 03
char* left_rotate(char* arr, int k) {
    assert(arr);
    char* ret = arr;
    int len = strlen(arr);
    k %= len;
    for (int i = 0; i < k; i++) {
        // rotate one character
        // 1
        char tmp = arr[0];
        // 2
        for (int j = 0; j < len - 1; j++) {
            arr[j] = arr[j + 1];
        }
        // 3
        arr[len - 1] = tmp;
    }
    return ret;
}
char* reverse(char* left, char* right) {
    char* ret = left;
    while (left < right) {
        char tmp = *left;
        *left = *right;
        *right = tmp;
        left++;
        right--;
    }
    return ret;
}
char* left_rotate2(char* arr, int k) {
    assert(arr);
    char* ret = arr;
    int len = strlen(arr);
    k %= len;
    // left part
    reverse(arr, arr + k - 1);
    // right part
    reverse(arr + k, arr + len - 1);
    // whole part
    reverse(arr, arr + len - 1);
    return ret;
}

// 04
void print_Yang_Hui_triangle(int lines) {
    int arr[10][10] = {0};
    for (int i = 0; i < lines; i++) {
        for (int j = 0; j <= i; j++) {
            if (j > 0 && j < i) {
                arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
            }else {
                arr[i][j] = 1;
            }
            printf("%3d ", arr[i][j]);
        }
        printf("\n");
    }
}

// 05
int Yang_matrix_find_num(int arr[3][3], int row, int col, int k) {
    int x = 0;
    int y = col - 1;
    while (x < row && y >= 0) {
        if (k < arr[x][y]) {
            y--;
        }
        else if (k > arr[x][y]) {
            x++;
        } else {
            return x * col + y;
        }
    }
    return -1;
}

// 06
int is_left_rotate(char* arr1, char* arr2) {
    int len1 = strlen(arr1);
    int len2 = strlen(arr2);
    if (len1 != len2) {
        return 0;
    }
    strncat(arr1, arr1, len1);
    char* ret = strstr(arr1, arr2);
    if (ret == NULL) {
        return 0;
    } else {
        return 1;
    }
}

// 07
// main implements

